<template>
  <div class="map">
    <div id="container">
    </div>
  </div>
</template>
<script>
export default {
  name: "position",
  data() {
    return {
      geolocation: new qq.maps.Geolocation(
        "OCNBZ-OZD63-EWO3V-3SPMP-EMPLE-EGF6R",
        "myapp"
      ),
      positionData: {},
      options: { timeout: 8000 },
      positionNum: 0
    };
  },
  mounted() {
   
    //   开启定位
      this.geolocation.getLocation(this.showPosition, this.showErr, this.options);
    this.showWatchPosition();
  
  },
  methods: {
    //初始化地图
    init() {
      var cityLocation,
        map,
        marker = null;
      var center = new qq.maps.LatLng( this.positionData.lat,this.positionData.lng); //设置地图中心点
      map = new qq.maps.Map(document.getElementById("container"), {
        //container:放置地图div的id属性
        center: center,
        zoom: 15 //地图缩放级别
      });
    //   调用城市服务信息
      cityLocation = new qq.maps.CityService({
        complete: function(results) {
          map.setCenter(results.detail.latLng);
          if (marker != null) {
            marker.setMap(null);
          }
          //设置marker标记
          marker = new qq.maps.Marker({
            map: map,
            position: results.detail.latLng
          });
        }
      });
    },
    //定位成功的回调函数
    showPosition(position) {
      this.positionData = position;
      console.log(this.positionData);
      if(this.positionData){
          this.init();
      };
        
    },
    //定位失败的回调函数
    showErr() {
      document.getElementById("container").innerHTML = "定位失败！" ;
    },
    //开始监听位置
    showWatchPosition() {
      this.geolocation.watchPosition(this.showPosition);
    },
    //停止监听位置
    showClearWatch() {
      this.geolocation.clearWatch();
    }
  }
};
</script>
<style scoped>
body {
  position: absolute;
  width: 100%;
  height: 100%;
  text-align: center;
}
#container {
  height: 100vh;
  font-size:.16rem;
  display:flex;
  justify-content: center;
  align-items: center;
  color:#cccccc;
}
button {
  margin-bottom: 10px;
  padding: 12px 8px;
  width: 42%;
  border-radius: 8px;
  background-color: #009ddc;
  color: white;
}
</style>


